package yannan.voiplock4ble.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import yannan.voiplock4ble.BuildConfig;
import yannan.voiplock4ble.download.ProgressResponseBody;
import yannan.voiplock4ble.download.ProgressResponseListener;
import yannan.voiplock4ble.eventbus.EventObject;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkService;
import yannan.voiplock4ble.utils.FileUtils;


/**
 * Created by PC on 2017/1/12.
 */

public class DownLoadService extends Service {
    private String url;
    //是否是强制更新
    private boolean isForce;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        url = intent.getStringExtra("url");
//        isForce = intent.getIntExtra("isForce", 0) == 0 ? false : true;
        downLoad();
        return super.onStartCommand(intent, flags, startId);
    }

    public NetworkService networkService;

    /**
     * 访问网络
     *
     * @return
     */
    public NetworkService getNetworkService(final ProgressResponseListener responseListener) {
        if (null == networkService) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(
                            new Interceptor() {
                                @Override
                                public okhttp3.Response intercept(Chain chain) throws IOException {
                                    //拦截
                                    okhttp3.Response originalResponse = chain.proceed(chain.request());
                                    //包装响应体并返回
                                    return originalResponse.newBuilder()
                                            .body(new ProgressResponseBody(originalResponse.body(), responseListener))
                                            .build();
                                }
                            }
                    )
                    .connectTimeout(30, TimeUnit.SECONDS).build();
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    //TODO 地址修改一下
                    .baseUrl(NetUtils.Base_Url_Down)
//                    .baseUrl("http://192.168.1.187:8080/")
                    .build();
            networkService = retrofit.create(NetworkService.class);
        }
        return networkService;
    }

    public void downLoad() {
        EventBus.getDefault().post(new EventObject(EventObject.UPDATEDOWNLOADAPKPROGRESS, 0));
        getNetworkService(new ProgressResponseListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
                EventBus.getDefault().post(new EventObject(EventObject.UPDATEDOWNLOADAPKPROGRESS, (int) bytesRead * 100 / (int) (contentLength)));
            }
        }).downLoadApk(url).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (BuildConfig.DEBUG) Log.e("ZipExtractorPresenter", "onResponse");
                try {
                    String fileType = response.body().contentType().subtype().equals("vnd.android.package-archive") ? "apk" : response.body().contentType().subtype();
                    FileUtils.saveFile(response.body().byteStream(), Environment.getExternalStorageDirectory() + "/vipLock",
                            "test." + fileType);
                    EventBus.getDefault().post(new EventObject(EventObject.DOWNLOADCOMPELTE, "下载完成了啊!"));
                    stopSelf();
                } catch (Exception e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new EventObject(EventObject.DOWNLOAD_FAILURE, "下载失败了啊！"));
                    stopSelf();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (BuildConfig.DEBUG) Log.e("ZipExtractorPresenter", "onFailure");
                EventBus.getDefault().post(new EventObject(EventObject.DOWNLOAD_FAILURE, "下载失败了啊！"));
                stopSelf();
            }
        });
    }

    @Override
    public void onDestroy() {
        System.out.println("服务自己结束掉了自己");
        super.onDestroy();
    }
}
